package org.jeecg.modules.submodules.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.submodules.entity.Car;
import org.jeecg.modules.submodules.entity.vo.CarStatisticsVo;
import org.jeecg.modules.submodules.entity.vo.GoodsStatisticsVo;
import org.jeecg.modules.submodules.service.IBigOrdersService;
import org.jeecg.modules.submodules.service.ICarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@RequestMapping("/statistics")
@Api(tags = "统计分析")
@RestController
@Slf4j
public class StatisticsController {
    @Autowired
    IBigOrdersService bigOrdersService;
    @Value("${jeecg.app.appPath}")
    private String apkPath;

    @Autowired
    ICarService carService;
    /**
     * 统计车辆接单数
     */
    @AutoLog("统计车辆接单数加平均接单数")
    @GetMapping("/getCarAndOrders")
    @ApiOperation(value = "统计车辆接单数加平均接单数")
    public Result<?> getCarAndOrders(CarStatisticsVo vo){
        return Result.ok(bigOrdersService.getCarReceivingOrders(vo));
    }
    /**
     * 统计货物实际重量
     */
    @AutoLog("统计货物实际重量")
    @GetMapping("/getAllGoodsWeight")
    @ApiOperation(value = "统计货物实际重量")
    public Result<?> getAllGoodsWeight(GoodsStatisticsVo vo){
        return Result.ok(bigOrdersService.getAllGoodsWeight(vo));
    }
    /**
     *  获取周转率
     */
    @AutoLog("获取周转率")
    @GetMapping("/getZhouzhuan")
    @ApiOperation(value = "获取周转率")
    public Result<?> getZhouzhuan(){
        String zhouzhuan = bigOrdersService.getZhouzhuan();
        if (StringUtil.isNullOrEmpty(zhouzhuan)){
            return Result.error("当日没有车次出动！无法计算周转率！");
        }
        return Result.ok(zhouzhuan);
    }
    /**
     *  获取每辆车平均载货量
     */
    @AutoLog("获取每辆车平均载货量")
    @GetMapping("/getAvgWeight")
    @ApiOperation(value = "获取每辆车平均载货量")
    public Result<?> getAvgWeight(String startDate,String endDate){
        List<Car> carList = carService.list();
        for (Car i : carList){
            i.setAvgWeightList(bigOrdersService.getAvgWeight(i.getId(),startDate,endDate));
        }
        return Result.ok(carList);
    }
    /**
     * 下载apk
     */
    @AutoLog("下载apk")
    @GetMapping("/download")
    @ApiOperation(value = "下载apk")
    public Result<?> downloadApk(HttpServletResponse response, HttpServletRequest request){
        String filePath = apkPath;
        File file = new File(filePath);
        if (file.exists()) {
            String fileName = "zhongyu_server.apk";
            response.setContentType("application/force-download;charset=UTF-8");
            final String userAgent = request.getHeader("USER-AGENT");
            try {
                if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Edge")) {// IE浏览器
                    fileName = URLEncoder.encode(fileName, "UTF8");
                } else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器
                    fileName = new String(fileName.getBytes(), "ISO8859-1");
                } else {
                    fileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
                }
                response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            } catch (UnsupportedEncodingException e) {
                return Result.error("");
            }
            InputStream in = null;
            OutputStream out = null;
            try {
                //获取要下载的文件输入流
                in = new FileInputStream(filePath);
                int len = 0;
                //创建数据缓冲区
                byte[] buffer = new byte[1024];
                //通过response对象获取outputStream流
                out = response.getOutputStream();
                //将FileInputStream流写入到buffer缓冲区
                while ((len = in.read(buffer)) > 0) {
                    //使用OutputStream将缓冲区的数据输出到浏览器
                    out.write(buffer, 0, len);
                }
                return Result.ok("文件下载成功！");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            return Result.error("该文件不存在");
        }
        return Result.ok("");
    }
}
